// 请求封装
function ajax(options) {
  var xhr = new XMLHttpRequest();
  var method = options.method || 'GET'; // 默认方法为GET
  var url = options.url;
  var data = options.data || null;
  var success = options.success || function() {};
  var error = options.error || function() {};
  var headers = options.headers || {};

  xhr.open(method, url, true);

  // 设置请求头
  for (var header in headers) {
    if (headers.hasOwnProperty(header)) {
      xhr.setRequestHeader(header, headers[header]);
    }
  }

  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      success(JSON.parse(xhr.responseText));
    } else {
      error(xhr.statusText);
    }
  };

  xhr.onerror = function() {
    error('Request failed');
  };

  if (method === 'GET' || !data) {
    xhr.send();
  } else if (method === 'POST') {
    // xhr.setRequestHeader('Content-Type', 'application/json'); // 或者 'application/json' 取决于你的后端期望的格式
    xhr.send(data); // data应为序列化后的字符串，例如encodeURIComponent(JSON.stringify(data))对于JSON数据
  }
}

// base64转File对象
function base64ToFile(base64Data, fileName, mimeType) {
  // 将Base64编码的字符串转换为原始的二进制数据
  const binaryString = window.atob(base64Data);
  // 创建一个字节数组
  const bytes = new Uint8Array(binaryString.length);
  // 将字节数组填充为原始的二进制数据
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  // 创建一个Blob对象
  const blob = new Blob([bytes], { type: mimeType });
  // 创建一个File对象
  const file = new File([blob], fileName, { type: mimeType });
  return file;
}

// 在线地址下载
async function downloadFile(url, fileName) {
  const response = await fetch(url);
  const blob = await response.blob();
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(link.href);
}

// 核心方法
const go = (sign) => {
  const imgList = document.querySelectorAll('.showScrollbar  .sm\\:w-1\\/4')
  const token = localStorage.getItem('token')

  imgList.forEach((item, index) => {
    const img = item.querySelector('img')
    const sizeElement = item.querySelector('.text-xs')
    const sizeStr = sizeElement.firstChild.innerText
    const [width, height] = sizeStr.split('*')
    const base64 = img.src
    // 拿到base64实体
    const base64Data = base64.split(',')[1];
    const fileName = `example_${index}.png`; // 文件名和扩展名
    const mimeType = 'image/png'; // MIME类型
    const file = base64ToFile(base64Data, fileName, mimeType);
    console.log(file); // 输出File对象

    const fd = new FormData()
    fd.append('name', 'avatar.png')
    fd.append('key', `${sign.dir}/example_${index}.png`)
    fd.append('dir', sign.dir)
    fd.append('token', sign.token)
    fd.append('response', 'inner')
    fd.append('file', file)
    ajax({
      url: sign.host, // 上传关键步骤 upload
      method: 'POST',
      data: fd,
      success: function(response) {
        console.log('Data submitted:', response);
        const image = response.key
        //
        const fd = new FormData()
        fd.append('image', image)
        fd.append('type', 'rmbg')
        fd.append('width', width)
        fd.append('height', height)
        fd.append('action', 'zero')
        fd.append('token', token)
        fd.append('captchacode',window.leshemModule ? window.leshemModule.ccall("get_code", "string", [], []) : "")
        fd.append('filename', '')
        fd.append('model', 3)
        fd.append('edge_enhancement', 0)
        ajax({
          url: 'https://www.koukoutu.com/api/segment',
          method: 'POST',
          data: fd,
          success: function(response) {
            console.log('segment Data submitted:', response);
            setTimeout(() => {
              const fd = new FormData()
              fd.append('type', 'rmbg')
              fd.append('token', token)
              fd.append('taskId', response.message.taskId)
              ajax({
                url: 'https://www.koukoutu.com/api/query',
                method: 'POST',
                data: fd,
                success: function(response) {
                  console.log('query Data submitted:', response);
                  const url = response.message.resultpath
                  downloadFile(url, `pic${index}.png`)
                }
              })
            }, 3000)
          }
        })
      },
      error: function(error) {
        console.error('Submitting data failed:', error);
      }
    });
  })
}

// 初始化
const init = () => {
    const fd = new FormData()
    fd.append('action', 'zero')
    fd.append('type', 'all')
    fd.append('token', '')
    ajax({
      url: 'https://www.koukoutu.com/api/oss/signature',
      method: 'POST',
      data: fd,
      success: function(response) {
        console.log('sign submitted:', response);
        go(response.message)
      }
    })
}

init()